function executeConcurrently(tasks, concurrency) {
    let activeCount = 0;
    let results = [];
    let hasError = false;

    function runTask(task) {
        return new Promise((resolve, reject) => {
            try {
                const taskPromise = task();
                if (taskPromise && typeof taskPromise.then === "function") {
                    taskPromise.then(resolve).catch(reject);
                } else {
                    resolve(task());
                }
            } catch (error) {
                reject(error);
            }
        })
            .then((result) => {
                results.push(result);
                activeCount--;
                scheduleNextTask();
            })
            .catch((error) => {
                hasError = true;
                results.push(error);
                activeCount--;
                scheduleNextTask();
            });
    }

    function scheduleNextTask() {
        if (activeCount < concurrency && tasks.length > 0) {
            activeCount++;
            const task = tasks.shift();
            runTask(task);
        }
    }

    // 立即开始执行任务
    while (activeCount < concurrency && tasks.length > 0) {
        scheduleNextTask();
    }

    // 返回一个Promise，当所有任务都完成或有错误发生时解决/拒绝
    return new Promise((resolve, reject) => {
        if (hasError) {
            reject(results);
        } else {
            resolve(results);
        }
    });
}

// 示例用法
const tasks = [
    // () => new Promise((resolve) => resolve("Task 1")),
    // () => new Promise((resolve) => resolve("Task 2")),
    // () => new Promise((resolve) => resolve("Task 3")),
    // () => Promise.resolve("Task 1"),
    // () => Promise.resolve("Task 2"),
    // () => Promise.resolve("Task 3"),
    new Promise((resolve) => setTimeout(() => resolve("Task1 "), 1000)),
    new Promise((resolve) => setTimeout(() => resolve("Task2 "), 2000)),
    new Promise((resolve) => setTimeout(() => resolve("Task3 "), 3000)),
    new Promise((resolve) => setTimeout(() => resolve("Task4 "), 500)),
];
const concurrency = 2;

executeConcurrently(tasks, concurrency)
    .then((results) => {
        console.log("All tasks completed with results:", results);
    })
    .catch((error) => {
        console.error("An error occurred:", error);
    });
